<template>
  <Header />
  <Menu />
  <div v-if="showPageContent" class="container-fluid">
    <div class="row text-center justify-content-center webtitle"></div>
    <div class="row justify-content-center">
      <el-form ref="chapterForm" :model="form" label-width="auto" @submit.prevent="updateChapter" style="max-width: 90%;">
        <el-form-item label="当前更新小说：">
          <el-input v-model="form.novel_name" clearable disabled></el-input>
        </el-form-item>
        <el-form-item label="最新章：">
          <el-input v-model="form.last_chapter_title" clearable disabled></el-input>
        </el-form-item>
        <el-form-item label="连更模式：">
          <el-checkbox v-model="ischecked" label="开启"></el-checkbox>
          &nbsp;&nbsp;<img src="@/assets/icon/question.png" class="haveques" @click="solveques">
        </el-form-item>
        <el-form-item label="新增章节标题：">
          <el-input v-model="form.chapter_title" clearable required></el-input>
        </el-form-item>
        <el-form-item label="章节内容：">
          <el-input type="textarea" v-model="form.chapter_content" :rows="contentRows" required></el-input>
        </el-form-item>
        <div class="twobtn">
          <el-button type="primary" native-type="submit">提交</el-button>
          <el-button @click="goBack">返回</el-button>
        </div>
      </el-form>


    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import {useRoute, useRouter} from 'vue-router';
import axios from 'axios';
import { ElNotification } from 'element-plus';
import Header from "@/components/Header.vue";
import Menu from "@/components/Menu.vue";
import VueCookies from "vue-cookies";
import config from "../../../config/config.js";

const showPageContent = ref(true);
const route = useRoute();
const router = useRouter();
const novelId = parseInt(router.currentRoute.value.params.novelId);

const ischecked = ref(true);
const lastid = ref('');

const form = ref({
  novel_name:'',
  last_chapter_title:'',
  chapter_title: '',
  chapter_content: '',
  chapter_novelID: novelId,
});

const userToken = VueCookies.get('userToken');
const headers = {
  Authorization: `Bearer ${userToken}`
};

const fetchNovelInfo = async () => {
  const novelId = route.params.novelId;
  const userToken = VueCookies.get('userToken');
  const apiUrl = `${config.apiUrl}/novel/info?novelId=${novelId}`;
  const headers = {
    Authorization: `Bearer ${userToken}`
  };

  try {
    const response = await axios.get(apiUrl, { headers });
    const novelInfo = response.data;
    if (response.status === 201) {
      ElNotification({
        message: novelInfo.message,
        type: 'warning',
        duration: 2000
      });
      showPageContent.value = false;
    } else {
      form.value.novel_name = novelInfo.novel_name;
      form.value.last_chapter_title = novelInfo.latest_chapter.chapter_title;
      lastid.value = novelInfo.latest_chapter.id;
    }
  } catch (error) {
    console.error('获取小说信息失败:', error);
    ElNotification({
      message: '暂无信息',
      type: 'warning',
      duration: 2000
    });
    router.back(); // 自动返回
  }
};

const updateChapter = async () => {
  if(form.value.chapter_content.length>50000){  //一章不得超过50000字
    console.log(form.value.chapter_content.length);
    ElNotification({
      message: '字数太多了，分开发吧！',
      type: 'error',
      duration: 2000
    });
    return;
  }
  const apiUrl = `${config.apiUrl}/novel-chapter/add`;
  try {
    const response = await axios.post(apiUrl, form.value, { headers });
    if (response.status === 200) {
      ElNotification({
        message: '章节更新成功！',
        type: 'success',
        duration: 2000
      });
      if(ischecked.value){
        fetchNovelInfo();
        form.value.chapter_title = '';
        form.value.chapter_content = '';
      }else{
        const newid = lastid.value + 1;
        router.push('/edit/chapter/'+newid);
      }

    } else {
      ElNotification({
        message: response.data.message || '章节更新失败！',
        type: 'error',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('章节更新失败:', error);
    ElNotification({
      message: '章节更新失败！',
      type: 'error',
      duration: 2000
    });
  }
};
const solveques = () =>{
  ElNotification({
    message: '开启后提交内容不跳转，关闭则会跳转到更新章节的编辑页！',
    type: 'success',
    duration: 3000
  });
}
const goBack = () => {
  router.back();
};

const contentRows = 35;
onMounted(fetchNovelInfo);
</script>

<style scoped>
.webtitle {
  font-size: 15px;
  padding: 10px;
}
.twobtn{
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}
.haveques{
  width: 17px;
  cursor: pointer;
}
</style>
